package com.zcs.app.lucky.ui.clip

import android.content.Intent
import android.graphics.Bitmap
import android.text.TextUtils
import android.view.ViewTreeObserver
import cn.sxw.android.base.kt.BaseNormalKtActivity
import cn.sxw.android.base.kt.BaseViewModel
import cn.sxw.android.base.utils.BitmapUtils
import cn.sxw.android.base.utils.JLogUtil
import com.safframework.delegate.extras.extraDelegate
import com.zcs.app.lucky.databinding.ActivityClipSquareBinding
import java.io.File
import java.util.*

/**
 * 头像裁剪 - 圆形预览
 *
 * @author ZengCS
 * @since 2015年1月26日17:40:42
 */
class AvatarClipActivity : BaseNormalKtActivity<ActivityClipSquareBinding, BaseViewModel>() {
    companion object {
        private const val TAG = "AvatarClipActivity/D"
        private const val AVATAR_SIZE = 480
    }

    private val path by extraDelegate("PATH", "")
    private val isCircle by extraDelegate("IS_CIRCLE", true)

    private val avatarCacheDir by lazy {
        getExternalFilesDir("Avatars")!!.absolutePath
    }

    // Variable
    private var currentUserAvatarPath: String? = null

    override fun onInit() {
        if (TextUtils.isEmpty(path)) {
            showExitMessageDialog("图片加载失败，请重试")
            return
        }
        initView()
        initObserve()
        initData()
    }

    override fun initView() {
        // 生成当前时间用户头像路径
        currentUserAvatarPath = avatarCacheDir + File.separator + "_" + UUID.randomUUID() + ".jpg"
        binding.clipOverlayView.setIsCircle(isCircle)

        binding.clipOverlayView.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                val width = binding.clipOverlayView.width
                val height = binding.clipOverlayView.height
                JLogUtil.d(TAG, "width = $width")
                JLogUtil.d(TAG, "height = $height")
                binding.clipOverlayView.viewTreeObserver.removeOnGlobalLayoutListener(this)
                showPic()
            }
        })
        val dir = File(avatarCacheDir)
        if (!dir.exists()) {
            dir.mkdirs()
        }
    }

    private fun showPic() {
        val bmp: Bitmap? = BitmapUtils.compressFile(this, path, 0)
        if (bmp != null) {
            binding.clipImageView.setIniting(false)
            binding.clipImageView.setImageBitmap(bmp)
            binding.clipOverlayView.openSpotlight()
        } else {
            onError("头像选取失败，请重试")
        }
    }

    override fun initData() {}
    override fun initObserve() {}

    override fun addOnClickListener() {
        binding.btnClipCancel.setOnClickListener {
            setResult(RESULT_CANCELED)
            finish()
        }
        binding.doneBtn.setOnClickListener {
            try {
                // 此处获取剪裁后的bitmap
                val bitmap = binding.clipImageView.clip()
                val saveBitmapSuccess: Boolean =
                    BitmapUtils.saveBitmapWithZoom(bitmap, currentUserAvatarPath, AVATAR_SIZE)
                if (saveBitmapSuccess) {
                    // 执行上传
                    onSuccess(currentUserAvatarPath)
                } else {
                    onError("图片保存失败")
                }
            } catch (e: Exception) {
                onError("图片保存失败")
            }
        }
    }

    private fun onSuccess(newAvatar: String?) {
        if (TextUtils.isEmpty(newAvatar)) {
            onError("头像裁剪失败，请重试")
            return
        }
        val intent = Intent()
        intent.putExtra("CLIP_AVATAR", currentUserAvatarPath)
        setResult(RESULT_OK, intent)
        finish()
    }

    private fun onError(msg: String) {
        setResult(RESULT_CANCELED)
        showExitMessageDialog(msg)
    }
}